package net.hnilice.excel;

import java.sql.Types;
import java.util.Collection;

public class IntArray
        extends SqlArrayAdapter {

    private static final Integer[] emptyArray = new Integer[0];
    private int[] array;

    public IntArray(int[] array) {
        if (array == null) {
            throw new IllegalArgumentException("parameter array should not be null");
        }
        this.array = array;
    }

    public IntArray(Collection<Integer> set) {
        if (set == null) {
            throw new IllegalArgumentException("parameter set should not be null");
        }
        Integer[] keys = set.toArray(emptyArray);

        this.array = new int[keys.length];
        for (int i = 0; i < keys.length; ++i) {
            Integer key = keys[i];
            this.array[i] = key.intValue();
        }
    }

    @Override
    public int getBaseType() // throws SQLException
    {
        return Types.INTEGER;
    }

    /**
     * This method is called by driver ver. 8 but not by ver. 7.
     */
    @Override
    public String getBaseTypeName() // throws SQLException
    {
        return "int4";
    }

    /**
     * This method is called by both drivers ver. 8 and 7.
     */
    @Override
    public String toString() {
        String result = "{";
        for (int i = 0; i < this.array.length; ++i) {
            if (i > 0) {
                result += ",";
            }
            result += this.array[i];
        }
        result += "}";
        return result;
    }

    public void free() // throws SQLException
    {
        this.array = null;
    }

}
